<?php
namespace App\Admin\Actions;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

trait Create
{

	public function store(Request $request, ActionSetter $setter)
	{
		abort_unless(method_exists($this, 'modelName'), 500, class_basename($this)." 未设置 modelName() 方法");

		// 默认配置器与自定义配置器
		$this->storeSetter($setter);

		// 获得验证数据
		$validated = $setter->call('validate', $request);

		// 前置操作
		$attributes = $setter->call('before', $request, $validated);

		// 数据入库
		$model = $setter->call('handle', $request, $attributes);
		abort_unless($model->getKey(), 500, '数据写入失败');

		// 后置操作
		$result = $setter->call('after', $model, $validated);

		return [
			'code' => 0,
			'message' => '创建成功',
			'data' => $result
		];
	}

	private function storeSetter($setter)
	{
		$setter->before(function($request, $validated){
			return $validated;
		});

		$setter->handle(function($request, $attributes){
			return $this->modelName()::create($attributes);
		});

		if( method_exists($this, 'actionStore') ){
			$this->actionStore($setter);
		}
		if( method_exists($this, 'storeAndUpdateValidate') ){
			$setter->validate([$this, 'storeAndUpdateValidate']);
		}
		abort_unless($setter->has('validate'), 500, 'store必须设置validate配置器');
	}
}

